﻿
$(function () {
    Vue.use(VueDragging)
    var vmHome = new Vue({
        el: "#Divhome",
        data: {
            InsiderIndex: "",// 常用弹框新增索引
            OutsiderIndex: "",// 通用弹框索引
            selectedRadioValue: "1",
            commouseContent: "",// 常用模块弹出框内容宽度
            bodyHeight: "", // 首页右侧的高度
            isCanHandle: true,// 默认该属性的禁止用户操作
            selectedTitleID: '',// 常用模块弹出框默认选中的标题
            searchInsiderLinks: '', // 搜索常用模块text
            searchOutsiderLinks: '', // 搜索外部模块text
            searchSelectedTitleItem: '', //搜索常用模块里弹出框text
            currentIndex: "0",
            selectedTitleInfo: [], // 用户在弹出框选中标题筛选的数据
            selectedEditInfo: [],// 模块选中的信息
            selectedItemInfo: [], /// 用户选中的模块信息
            UserLinksInfo: [], // 用户配置模块信息
            UserInsiderLinksInfo: [], // 常用模块链接信息
            UserOutsiderLinksInfo: [], // 外部站点链接信息
            UserLinksInfoQery: {
                pageIndex: 1,
                pageSize: 9999,
                order: "userFunctionSetSort asc,createTime desc",
                filter: {
                    type: "and",
                    conditions: [
                        {
                            attribute: "userGUID",
                            datatype: "uniqueidentifier",
                            operatoer: "eq",
                            value: $.dm.getUserInfo().id
                        }
                    ]
                }
            },
            linksInfo: {
                id: null,
                userGUID: $.dm.getUserInfo().id,
                isSiteInner: null,
                userFunctionSetUrl: null,
                userFunctionSetSiteIcon: null,
                userFunctionSetName: null,
                functionGUID: null,
                IsBroswerOpen: "0",
                userFunctionSetSort: null,
            },
            InsiderInfoAllModuleName: [], // 常用模块的所有模块
            InsiderInfoAllModuleContent: [], // 常用模块的子模块的具体模块
            modules: [],
            selectModuleId: ''
        },
        methods: {
            // 获取用户配置模块信息
            getUserLinksInfo: function () {
                var self = this;
                var data = self.UserLinksInfoQery;
                var options = {
                    url: '/api/services/app/FWUserFunctionSet/GetViewPage',
                    data: data,
                    maskJqSelect: '#Divhome',
                };
                var success = function (result) {
                    self.UserInsiderLinksInfo = [];
                    self.UserOutsiderLinksInfo = [];
                    self.UserLinksInfo = result.dataList
                    for (var i = 0; i < self.UserLinksInfo.length; i++) {
                        if (self.UserLinksInfo[i].isSiteInner == "1") {
                            self.UserInsiderLinksInfo.push(self.UserLinksInfo[i])
                        } else {
                            self.UserOutsiderLinksInfo.push(self.UserLinksInfo[i])
                        }
                    }
                    self.UserInsiderLinksInfo = _.orderBy(self.UserInsiderLinksInfo, function () {
                        return ['userFunctionSetSort', 'createTime'], ['asc', 'asc']
                    })
                    self.UserOutsiderLinksInfo = _.orderBy(self.UserOutsiderLinksInfo, function () {
                        return ['userFunctionSetSort', 'createTime'], ['asc', 'asc']
                    })
                    self.$nextTick(function () {
                        insiderHover();
                        outsiderHover();
                    });
                }
                abp.ajax(options).done(success);
            },
            getSelectedLinksInfo: function () {
                var self = this
                var selectedTitleID = this.selectedTitleID
                var selectedTitleInfoTmp = []
                for (var i in self.InsiderInfoAllModuleContent) {
                    if (selectedTitleID == "QB") {
                        self.selectedTitleInfo = self.InsiderInfoAllModuleContent
                    } else {
                        if (selectedTitleID == self.InsiderInfoAllModuleContent[i].applicationGUID) {
                            selectedTitleInfoTmp.push(self.InsiderInfoAllModuleContent[i]);
                            self.selectedTitleInfo = selectedTitleInfoTmp
                        }
                    }
                }

            },
            // 搜索常用模块里selected的标题的子项目
            searchInsidderselectedTitleItem: function () {
                var self = this;
                var searchSelectedTitleItem = self.searchSelectedTitleItem;
                var InsiderInfoAllModuleContentDeepCopy = JSON.parse(JSON.stringify(self.InsiderInfoAllModuleContent));
                var selectedTitleInfoDeepCopy = JSON.parse(JSON.stringify(self.selectedTitleInfo));
                var functionInfos = [];
                if (self.selectModuleId === "QB") {
                    functionInfos = InsiderInfoAllModuleContentDeepCopy;
                } else {
                    functionInfos = selectedTitleInfoDeepCopy;
                }
                self.selectedTitleInfo = _(functionInfos).filter(function (item) {
                    item.myChildFuntion = _.filter(item.myChildFuntion,
                        function (childItem) { return childItem.functionName.indexOf(searchSelectedTitleItem) != -1 });
                    if (item.myChildFuntion.length > 0) {
                        return true;
                    } else {
                        return false;
                    }
                }).value();
            },
            // 获取常用模块信息
            getInsiderInfo: function (el) {
                var self = this;
                self.$nextTick(function () {
                    if (el == "addInsiderLinks") {
                        var title = $.dm.L("常用模块新增")
                    }
                    $("#saveInsiderLinksInfo").removeAttr("disabled");
                    $("#saveInsiderLinksInfo").text("保存");
                    self.InsiderIndex = layer.open({
                        type: 1,
                        title: title,
                        area: ['800px', '600px'],
                        scrollbar: false,
                        content: $("#insiderLinks"),
                        success: function () {
                            var index = layer.load(2);
                            var data = {
                                userGUID: $.dm.getUserInfo().id
                            }
                            var options = {
                                url: '/api/services/app/FWUser/GetUserSetFunction',
                                data: data,
                            };
                            var success = function (result) {
                                self.selectedItemInfo = result.chooseMyFunctions;
                                self.InsiderInfoAllModuleName = result.userSetModuleMyApplications;
                                self.modules = result.userSetModuleMyMudules;
                                self.InsiderInfoAllModuleName.unshift({
                                    id: "QB",
                                    applicationName: $.dm.L("全部系统")
                                })
                                self.modules.unshift({
                                    moduleGUID: "QB",
                                    moduleName: $.dm.L("全部模块"),
                                    applicationGUID: "QB"
                                })
                                self.InsiderInfoAllModuleContent = result.userSetModuleMyFunctions;
                                self.selectedTitleInfo = self.InsiderInfoAllModuleContent;
                                self.selectedTitleID = self.InsiderInfoAllModuleName[0].id;
                                self.selectModuleId = self.modules[0].moduleGUID;
                                layer.close(index);
                            }
                            abp.ajax(options).done(success);
                        }

                    });
                    setHover();
                });

            },
            //打开常用模块的弹出框
            openInsiderPopup: function (el) {
                this.getInsiderInfo(el)
            },
            openPopup: function (data, el, callBack) {
                if (el == "editInsiderLinkItem") {
                    var title = $.dm.L("常用模块编辑")
                    this.isCanHandle = true
                } else if (el == 'editOutsiderLinks') {
                    var title = $.dm.L("外部站点编辑")
                    this.isCanHandle = true
                } else if (el == "addOutsiderLinks") {
                    var title = $.dm.L("外部站点新增")
                    this.isCanHandle = true
                    this.linksInfo = {}
                }
                $("#saveLinksInfo").removeAttr("disabled");
                $("#saveLinksInfo").text($.dm.L("保存"));
                this.OutsiderIndex = layer.open({
                    type: 1,
                    title: title,
                    area: ['500px', '310px'],
                    scrollbar: false,
                    content: $("#outLinks"),
                    success: function () {
                        if (callBack) {
                            callBack()
                        }
                    }
                });
            },
            // 打开外部站点弹框
            openOutsiderPopup: function (item, el) {
                var selectedRadioValue = '1'
                var callback = function () {
                    layui.use('form', function () {
                        var form = layui.form;
                        $("#insider").prop("checked", selectedRadioValue == 0 ? true : false);
                        $("#out").prop("checked", selectedRadioValue == 1 ? true : false);
                        form.render(); //更新全部
                    });
                }
                this.openPopup(item, el, callback);
            },
            // 关闭常用模块的弹出框
            closeSelectedInsideLinks: function () {
                layer.close(this.InsiderIndex);
            },
            // 保存用户选中的常用模块信息（常用模块的新增）
            saveSelectedInsideLinks: function () {
                var self = this;
                var functionGUIDs = [];
                for (var i = 0; i < vmHome.$data.selectedItemInfo.length; i++) {
                    functionGUID = vmHome.$data.selectedItemInfo[i].id;
                    functionGUIDs.push(functionGUID);
                }
                $("#saveInsiderLinksInfo").attr("disabled", "disabled");
                $("#saveInsiderLinksInfo").text($.dm.L("保存中..."));
                var data = {
                    functionGUIDs: functionGUIDs,
                    userGUID: $.dm.getUserInfo().id
                };
                var options = {
                    url: '/api/services/app/FWUserFunctionSet/BatchSaveFunction',
                    data: data,
                };
                var success = function (result) {
                    setTimeout(function () {
                        layer.close(self.InsiderIndex);
                    }, 1000)
                    self.getUserLinksInfo();
                }
                abp.ajax(options).done(success);
            },
            // 常用模块的编辑
            editInsiderLink: function (item, el) {
                var self = this
                self.selectedEditInfo = item
                self.linksInfo = {}
                self.linksInfo.id = item.id
                self.linksInfo.userFunctionSetName = item.userFunctionSetName
                self.linksInfo.userFunctionSetUrl = item.userFunctionSetUrl
                self.openPopup("", el)
            },
            // 外部站点的编辑
            editOutsiderLink: function (item, el) {
                var self = this;
                self.selectedEditInfo = item;
                self.linksInfo = {};
                self.linksInfo.id = item.id;
                self.linksInfo.userFunctionSetName = item.userFunctionSetName;
                self.linksInfo.userFunctionSetUrl = item.userFunctionSetUrl;
                var callback = function () {
                    layui.use('form', function () {
                        var form = layui.form;
                        $("#insider").prop("checked", item.isBroswerOpen == 1 ? true : false);
                        $("#out").prop("checked", item.isBroswerOpen == 0 ? true : false);
                        form.render(); //更新全部
                    });
                }
                self.openPopup(item, el, callback)
            },
            // 修改模块链接
            saveLinksInfo: function () {

                var self = this;
                var data = self.linksInfo;
                var currentTitle = $("#Divhome .layui-layer-title").text().trim();
                if (!data.userFunctionSetName) {
                    layer.msg($.dm.L("站点名称不能为空！"));
                    return
                }
                if (data.userFunctionSetUrl && currentTitle !== $.dm.L("常用模块编辑")) {
                    var result = self.regWebUrl(data.userFunctionSetUrl)
                    if (result == false) {
                        layer.msg($.dm.L("请输入正确的域名格式！"));
                        return
                    }
                    if (currentTitle == "外部站点新增") {
                        var msg = self.removeAlikeData(data.userFunctionSetUrl);
                        if (msg == false) {
                            layer.msg($.dm.L("该链接已存在！"));
                            return
                        }
                    }
                }
                if (currentTitle == "常用模块编辑") {
                    data.isSiteInner = "1";
                    data.functionGUID = self.selectedEditInfo.functionGUID;
                    $("#saveLinksInfo").attr("disabled", "disabled");
                    $("#saveLinksInfo").text("保存中...");
                    var options = {
                        url: '/api/services/app/FWUserFunctionSet/UpdateByDto',
                        data: data,
                    };
                    var success = function (result) {
                        layer.msg($.dm.L("常用模块修改成功"));
                        setTimeout(function () {
                            layer.close(self.OutsiderIndex);
                        }, 500);
                        var editItem = _(self.searchInsiderInfos).find(x => x.id == data.id);
                        editItem.userFunctionSetName = data.userFunctionSetName;
                    }
                    abp.ajax(options).done(success);
                } else if (currentTitle == "外部站点新增") {
                    delete data.id
                    data.userGUID = $.dm.getUserInfo().id;
                    data.isSiteInner = "0";
                    data.IsBroswerOpen = parseInt(self.selectedRadioValue);
                    $("#saveLinksInfo").attr("disabled", "disabled");
                    $("#saveLinksInfo").text($.dm.L("保存中..."));
                    var options = {
                        url: '/api/services/app/FWUserFunctionSet/CreateByDto',
                        data: data,
                    };
                    var success = function (result) {
                        layer.msg($.dm.L("新增外部站点成功！"));
                        setTimeout(function () {
                            layer.close(self.OutsiderIndex);
                        }, 1000)
                        self.getUserLinksInfo();
                    }
                    abp.ajax(options).done(success);
                } else if (currentTitle == $.dm.L("外部站点编辑")) {
                    data.isSiteInner = "0";
                    data.isBroswerOpen = parseInt(self.selectedRadioValue);
                    $("#saveLinksInfo").attr("disabled", "disabled");
                    $("#saveLinksInfo").text("保存中...");
                    var options = {
                        url: '/api/services/app/FWUserFunctionSet/UpdateByDto',
                        data: data,
                    };
                    var success = function (result) {
                        layer.msg($.dm.L("外部站点修改成功！"));
                        setTimeout(function () {
                            layer.close(self.OutsiderIndex);
                        }, 1000)
                        var editItem = _(self.searchOutsiderInfos).find(x => x.id == data.id);

                        Object.assign(editItem, data);
                    }
                    abp.ajax(options).done(success);
                }
            },
            // 关闭弹出框
            closeLinksInfo: function () {
                layer.close(this.OutsiderIndex);
            },
            // 删除常用模块链接
            deleInsiderLink: function (item) {
                var query = {
                    id: item.id
                }
                this.deleLinkInfo(query, 'insiderLink')
            },
            // 删除外部站点链接
            deleOutsiderLink: function (item) {
                var query = {
                    id: item.id
                }
                this.deleLinkInfo(query, 'outsiderLink')
            },
            // 删除链接
            deleLinkInfo: function (query, el) {
                var self = this;
                // 关闭提示弹出框
                layer.confirm($.dm.L('您确定要删除这条链接吗？'), {
                    btn: [$.dm.L("确定"), $.dm.L("取消")]
                }, function () {
                    layer.closeAll('dialog');
                    var data = query;
                    abp.ajax({
                        url: '/api/services/app/FWUserFunctionSet/DeleteByDto',
                        data: data
                    }).done(function (result) {
                        if (el == 'insiderLink') {
                            var userLinksInfo = _.orderBy(self.UserInsiderLinksInfo, ['userFunctionSetSort', 'createTime'], ['asc', 'asc']);
                            _.remove(userLinksInfo, function (item) {
                                return item.id == query.id;
                            });
                            self.UserInsiderLinksInfo = userLinksInfo;
                        } else {
                            var userLinksInfo = _.orderBy(self.UserOutsiderLinksInfo, ['userFunctionSetSort', 'createTime'], ['asc', 'asc']);
                            _.remove(userLinksInfo, function (item) {
                                return item.id == query.id;
                            });
                            self.UserOutsiderLinksInfo = userLinksInfo;
                        }
                    });

                });
            },
            //打开常用模块链接地址
            openInsiderLinks: function (item) {
                var title = item.userFunctionSetName
                var url = item.userFunctionSetUrl
                var icons = item.userFunctionSetSiteIcon
                this.openNewTab(title, url, icons)
            },
            //打开外部站点链接地址
            openOutsiderLinks: function (item) {
                var title = item.userFunctionSetName
                var url = item.userFunctionSetUrl
                if (item.isBroswerOpen == 1) {
                    window.open(url, "_blank")
                } else {
                    this.openNewTab(title, url)
                }
            },
            // 打开链接的数据
            openNewTab: function (title, url, icons) {
                title = $.dm.L(title);
                $.ei.openNewTab(title, url, icons);
            },
            // 常用模块新增弹出框 中间内容模块操作
            childFunctionClick: function (childFunctionItem) {
                childFunctionItem.isChoose = !childFunctionItem.isChoose;
                var chooseFunctionItem = childFunctionItem;
                if (childFunctionItem.isChoose == false) {
                    _.remove(this.selectedItemInfo, function (selectItem) {
                        return selectItem.id == chooseFunctionItem.id;
                    });
                } else {
                    this.selectedItemInfo.push(chooseFunctionItem);
                }

            },
            // 常用模块新增弹出框 顶部选中模块操作
            deleteFunction: function (deleteFunctionItem) {
                _.remove(this.selectedItemInfo, function (selectItem) {
                    return selectItem.id == deleteFunctionItem.id;
                });
                var allFunctionItem = this.InsiderInfoAllModuleContent;
                for (var i = 0; i < allFunctionItem.length; i++) {
                    var chidlFunctions = allFunctionItem[i].myChildFuntion;
                    for (var j = 0; j < chidlFunctions.length; j++) {
                        if (deleteFunctionItem.id == chidlFunctions[j].id) {
                            chidlFunctions[j].isChoose = !chidlFunctions[j].isChoose;
                            return;
                        }
                    }
                }
            },
            // 校验域名方法
            regWebUrl: function (value) {
                var reg = /((https|http|ftp|rtsp|mms):\/\/)?(([0-9a-z_!~*'().&=+$%-]+:)?[0-9a-z_!~*'().&=+$%-]+@)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-z_!~*'()-]+\.)*([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.[a-z]{2,6})(:[0-9]{1,4})?((\/?)|(\/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+\/?)/g;
                var result = reg.exec(value);
                if (!result) {
                    return false
                } else {
                    return true
                }
            },
            // 去重方法
            removeAlikeData: function (key) {
                var self = this
                var msg;
                _.forEach(self.UserLinksInfo, function (item, index, array) {
                    if (item.userFunctionSetUrl == key) {
                        msg = false
                        return;
                    }
                });
                return msg
            },
        },
        mounted: function () {
            var self = this;
            this.getUserLinksInfo();
            this.bodyHeight = parent.$(".tabs-panels").height() - 26;
            this.$nextTick(function () {
                self.$dragging.$on('dragged', function (value) {
                    var value = value.value;
                    var sortParam = _.map(value.list, function (item, num, array) {
                        return {
                            id: item.id,
                            userFunctionSetSort: num
                        }
                    });

                    var options = {
                        url: '/api/services/app/FWUserFunctionSet/BatchSaveOrderRule',
                        data: {
                            dtos: sortParam
                        }
                    };
                    var success = function (result) {
                    }
                    abp.ajax(options).done(success);
                })

            });
        },
        computed: {
            seelctModules: function () {
                var self = this;
                var myModules = [];
                myModules = _.filter(self.modules, function (item, index, lst) {
                    if (self.selectedTitleID == "QB") {
                        return true;
                    } else {
                        return item.applicationGUID == self.selectedTitleID
                    }
                });
                if (myModules.length > 0) {
                    self.selectModuleId = myModules[0].moduleGUID;
                } else {
                    self.selectModuleId = null;
                }
                return myModules;
            },
            // 查询外部链接数据
            searchInsiderInfos: function () {
                var self = this;
                var result = _(this.UserInsiderLinksInfo).filter(function (item) {
                    if (!self.searchInsiderLinks) {
                        return true;
                    } else {
                        return item.userFunctionSetName.indexOf(self.searchInsiderLinks) != -1
                            || (item.functionSetFirstLeShort || '').toLowerCase().indexOf(self.searchInsiderLinks.toLowerCase()) != -1
                            || (item.functionSetPinYin || '').indexOf(self.searchInsiderLinks) != -1;
                    }
                }).value();

                self.$nextTick(function () {
                    insiderHover();
                });
                return result;
            },
            // 查询内部链接数据
            searchOutsiderInfos: function () {
                var self = this;
                var datas = this.UserOutsiderLinksInfo;
                var searchText = this.searchOutsiderLinks;

                var result = _(datas).filter(function (item) {
                    if (!searchText) {
                        return true;
                    } else {
                        return item.userFunctionSetName.indexOf(searchText) != -1
                            || (item.functionSetFirstLeShort || '').toLowerCase().indexOf(searchText.toLowerCase()) != -1
                            || (item.functionSetPinYin || '').indexOf(searchText) != -1;
                    }
                }).value();
                self.$nextTick(function () {
                    outsiderHover();
                });
                return result;
            }
        },
        watch: {
            searchSelectedTitleItem: function () {
                this.searchInsidderselectedTitleItem()
            },
            selectModuleId: function (newvalue, oldValue) {
                var self = this;
                var InsiderInfoAllModuleContentDeepCopy = JSON.parse(JSON.stringify(self.InsiderInfoAllModuleContent));
                self.selectedTitleInfo = _(InsiderInfoAllModuleContentDeepCopy).filter(function (item) {
                    if (self.selectModuleId == "QB") {
                        return true;
                    } else {
                        return item.moduleGUID == newvalue;
                    }
                }).value();
            }
        }
    });
    // 获取当前索引
    layui.use('element', function () {
        var element = layui.element;
        element.on('tab(tabChange)', function (data) {
            vmHome.$data.currentIndex = data.index
        });
    });
    // 监听单选框
    layui.use('form', function () {
        var form = layui.form;
        // 监听radio事件
        form.on('radio(radioItem)', function (data) {
            var radioValue = data.value;
            vmHome.$data.selectedRadioValue = radioValue
        });
    });

    // 常用模块hover事件
    function insiderHover() {
        $(".insider_link_info .insider_link_info_list li .insider_link_info_list_img").hover(function () {
            $(this).find("span.iconPic").show();
            $(this).find(".user_handle").show();
        }, function () {
            $(this).find("span.iconPic").show();
            $(this).find(".user_handle").hide();
        });
    };
    // 外部站点hover事件
    function outsiderHover() {
        $(".insider_link_info .insider_link_info_list li .insider_link_info_list_img").hover(function () {
            $(this).find("img").show();
            //$(this).find("img:after").show();
            $(this).find(".user_handle1").show();
        }, function () {
            $(this).find("img").show();
            //$(this).find("img:after").show();
            $(this).find(".user_handle1").hide();
        });

    };
    // 常用模块弹出层hove事件
    function setHover() {
        // 内部链接弹出框标题选择操作
        $(document).on("mouseover mouseout", ".commonuse_title .title_item", function (event) {
            if (event.type == "mouseover") {
                $(this).find(".delete_icon").hide()
                $(this).find(".layui-icon-close-fill").show()
            } else if (event.type == "mouseout") {
                $(this).find(".delete_icon").show()
                $(this).find(".layui-icon-close-fill").hide()
            }
        })
        // 内部链接弹出框内容子模块选择操作
        $(document).on("mouseenter mouseleave", ".commonuse_main_content_Info .commonuse_main_content_list .commonuse_main_content_list_item", function (event) {
            if (event.type == "mouseenter") {
                $(this).children(".grayColor").removeClass("grayColor").addClass("greenColor addIconBorder ")
                $(this).addClass("greenColor")
            } else if (event.type == "mouseleave") {
                $(this).children(".greenColor .addIconBorder ").removeClass("greenColor addIconBorder").addClass("grayColor")
                $(this).removeClass("greenColor")
            }
        })
    }

})

